class Notifier {
    constructor() {
        this.observers = {
            // key: [fn,fn...] 一个key下可以有多个观察者
        };
    }

    addObserver(key, fn) {
        let handlers = this.observers[key];
        if (handlers === undefined) {
            handlers = [];
            this.observers[key] = handlers;
        }
        handlers.push(fn);
    }

    removeObverser(key, fn) {
        const handlers = this.observers[key];
        if (!handlers) return;
        this.observers[key] = handlers.filter(observer => observer != fn);
    }

    notify(key, data) {
        const handlers = this.observers[key];
        if (handlers === undefined) return;
        handlers.forEach(observer => {
            observer(data);
        });
    }
}

export const notifier = new Notifier();
